<!--
 * @Description: APP管理
 * @Author: fxg
 * @Date: 2020-06-29 11:18:28
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-03-18 09:30:40
-->
<template>
  <div class="pages_content table APPmanagement">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main>
        <div class="header_right" @click="showCardNav = !showCardNav">
          <div class="title">搜索</div>
          <div>
            <div :class="{ 'arrowTransform': !showCardNav, 'arrowTransformReturn': showCardNav}">
              <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
            </div>
          </div>
        </div>
        <div v-show="showCardNav" class="hr"></div>
        <el-collapse-transition>
          <div v-show="showCardNav" class="search">
            <div style="padding: 20px;">
              <span style="margin-right: 24px;">
                <span style="margin-right: 12px;">名称</span>
                <el-input v-model="tableParam.name" style="width: 20%;max-width: 200px;" clearable placeholder="请输入" />
              </span>
              <span>
                <span style="margin-right: 12px;">编码</span>
                <el-input v-model="tableParam.code" style="width: 20%;max-width: 200px;" clearable placeholder="请输入" />
              </span>
              <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="(tableParam.page = 1), queryPage()">查 询</el-button>
              <el-button size="medium" class="bottom_all_two" @click="reset()">重 置</el-button>
            </div>
          </div>
        </el-collapse-transition>
        <div class="hr"></div>
        <div class="card">
          <div class="card_nav">
            <div>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0;" @click="add()">
                <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                添加
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='SHANCHU'))!==-1" size="small" class="bottom_two" @click="batchUpdateOrDelete('update_status', 0)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                删除
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='RIYONG'))!==-1" size="small" class="bottom_three" @click="batchUpdateOrDelete('update_enable', 1)">
                <i class="icon iconfont iconicon_button_startuse" style="font-size: 12px;"></i>
                启用
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='JINYONG'))!==-1" size="small" class="bottom_four" @click="batchUpdateOrDelete('update_enable', 0)">
                <i class="icon iconfont iconicon_button_disable1" style="font-size: 12px;"></i>
                禁用
              </el-button>
            </div>
            <div>
              <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='BAOCUNPXH'))!==-1" :underline="false" @click="updateSortNum()">
                <span class="el-icon--left">
                  <i class="iconfont iconicon_button_sort1"></i>
                </span>
                保持排序号
              </el-link>
              <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px;">
                <el-link :underline="false">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_filtrate"></i>
                  </span>
                  筛选
                </el-link>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="(item, index) in table" :key="index">
                    <el-checkbox v-model="item.status">{{ item.label }}</el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='DAOCHU'))!==-1" :underline="false" @click="$Download(DownloadURL, tableParam)">
                <span class="el-icon--left">
                  <i class="iconfont iconicon_button_export1"></i>
                </span>
                导出
              </el-link>
            </div>
          </div>
          <div class="card_info" :style="style">
            <el-table ref="multipleTable" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
              <el-table-column align="center" type="selection" width="50"></el-table-column>
              <template v-for="(item, index) in table">
                <el-table-column v-if="item.status" :key="index" :label="item.label" align="center" :width="item.width">
                  <template slot-scope="scope">
                    <el-button v-if="item.label == '安装包'&&scope.row.appPackage&&ButtonList.findIndex(res=>(res.buttonValue=='XIAZAZB'))!==-1" class="bottom_one" size="mini" @click="Download(scope.row.appPackage)">安装包</el-button>
                    <span v-else-if="item.label == '状态'">
                      <span v-if="scope.row.enable == 0" style="color:#969799;">禁用</span>
                      <span v-if="scope.row.enable == 1 " style="color:#00A754;">启用</span>
                    </span>
                    <span v-else-if="item.label == '下载二维码'&&ButtonList.findIndex(res=>(res.buttonValue=='EWEIM'))!==-1">
                      <el-button v-if="scope.row.qrCode" class="bottom_one" size="mini" @click="qrcode(scope.row.qrCode)">二维码</el-button>
                    </span>
                    <el-button v-else-if="item.label == '操作'&&ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" class="bottom_one" size="mini" @click="update(scope.row)">
                      <i class="icon iconfont iconicon_button_modification" style="font-size: 12px;"></i>修改
                    </el-button>
                    <span v-else>{{ scope.row[item.prop] }}</span>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
          <div class="card_bottom">
            <div class="card_bottom_left">
              <div class="top_page_totle">总共{{ total }}条</div>
              <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" layout="prev, pager, next, jumper" :total="total" @current-change="queryPage()"></el-pagination>
            </div>
            <div>
              <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="queryPage()">刷新</el-button>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="dialogVisible" width="680px" :before-close="resefrom" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">{{ dialogtitle }}</span>
      <div class="dialoginfo">
        <el-form ref="dialogForm" v-loading="TreeLoading" :rules="rules" :inline="true" :model="from" label-width="90px">
          <el-form-item prop="code">
            <span slot="label" style="color:  #FF0000 ;">APP编码</span>
            <el-input v-model="from.code" placeholder="请输入" clearable @input="changecode('code')"></el-input>
          </el-form-item>
          <el-form-item prop="name">
            <span slot="label" style="color:  #FF0000 ;">APP名称</span>
            <el-input v-model="from.name" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item prop="version">
            <span slot="label">APP版本</span>
            <el-input-number v-model="from.version" :controls="false" :precision="0" style="width:200px;" :disabled="dialogtitle == '修改APP'"></el-input-number>
          </el-form-item>
          <el-form-item prop="appTypeId">
            <span slot="label">APP类型</span>
            <el-select v-model="from.appTypeId" placeholder="请选择">
              <el-option v-for="item in appType" :key="item.id" :label="item.itemName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="url">
            <span slot="label">URL</span>
            <el-input v-model="from.url" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item prop="sortNum">
            <span slot="label">排序号</span>
            <el-input v-model="from.sortNum" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <div>
            <el-form-item label="二维码">
              <el-upload class="avatar-uploader" action="/resource/resources/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="upheader">
                <img v-if="imageUrl" :src="'/file/'+imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="安装包">
              <div class="app">
                <el-upload action="/resource/resources/upload" :show-file-list="true" :before-upload="beforeAvatarUpload1" :on-success="handleAvatarSuccess1" :file-list="appPackage" :headers="upheader">
                  <el-button class="bottom_one">上传</el-button>
                  <span style="padding-left:10px">{{from.appPackage}}</span>
                </el-upload>
              </div>
            </el-form-item>
          </div>
          <el-form-item label="状态" prop="enable">
            <el-radio-group v-model="from.enable">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="from.remark" placeholder="请填写备注" class="textarea" type="textarea" resize="none" rows="5"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resefrom()">取 消</el-button>
        <el-button class="bottom_all" @click="save()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog v-dialogDrag :visible.sync="qrimgvis" width="300px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">二维码</span>
      <div>
        <img :src="qrimg" style="width:220px;height:220px; margin: 0 auto" class="avatar">
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" style="margin:0;" @click="qrimgvis=false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import breaDcrumb from "@/components/breadcrumb";
import { mapGetters } from "vuex";
import {
  queryPage,
  saveOrUpdate,
  batchUpdateOrDelete,
  updateSortNum, Download,
} from "@/api/basedata/APPmanagement.js";
import { getDicType } from "@/api/common.js";
import { sortReg, codeReg } from "@/common/RegExp.js";
import { getToken, getUserId } from '@/utils/auth';
export default {
  components: {
    breaDcrumb,
  },
  data() {
    var validatePass1 = (rule, value, callback) => {
      if (sortReg(value)) {
        callback();
      } else {
        callback(new Error("请输正整数序号!"));
      }
    };
    return {
      upheader: {
        "access-token": getToken(),
        "user-id": getUserId(),
      },
      DownloadURL: Download,
      /*添加修改弹窗*/
      dialogVisible: false,
      dialogtitle: "添加APP",
      appType: [],
      /*弹要修改过着添加的数据*/
      from: {
        name: "",
        code: "",
        version: "",
        //type: 0,
        url: "",
        remark: "",
        appPackage: "",
        sortNum: "",
        enable: 1,
        appTypeId: "",
        qrCode: '',
      },
      appPackage: [],
      /*判断收起展开*/
      showCardNav: true,
      /*搜索关键字段*/
      /*列表展示*/
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入编码", trigger: "blur" }],
        appTypeId: [
          { required: true, message: "请选择APP类型", trigger: "change" },
        ],
        version: [
          { required: true, message: "请输入APP版本", trigger: "blur" },
        ],
        url: [{ required: true, message: "请输入URl", trigger: "blur" }],
        sortNum: [{ required: true, message: "请输入排序号", trigger: "blur" },
        { validator: validatePass1, trigger: "blur", }
        ],
      },
      table: [
        { label: "APP编码", width: "auto", prop: "code", status: true },
        { label: "APP名称", width: "auto", prop: "name", status: true },
        { label: "APP版本", width: "auto", prop: "version", status: true },
        { label: "APP类型", width: "auto", prop: "appTypeName", status: true },
        { label: "URL", width: "auto", prop: "url", status: true },
        { label: "备注", width: "auto", prop: "remark", status: true },
        { label: "下载二维码", width: "auto", prop: "qrCode", status: true },
        { label: "安装包", width: "auto", prop: "", status: true },
        { label: "排序号", width: "auto", prop: "sortNum", status: true },
        { label: "状态", width: "auto", prop: "", status: true },
        { label: "操作", width: "120", prop: "", status: true },
      ],
      /*列表选中的数据集*/
      tableParam: {
        page: 1,
        pageSize: 12,
        code: "",
        name: "",
      },
      total: 0,
      ids: [],
      sortIds: [],
      tableData: [],
      imageUrl: '',
      qrimg: '',
      qrimgvis: false,
      ButtonList: [],
      TreeLoading: false
    };
  },
  mounted() {
    this.ButtonList = this.$ButtonList()
    getDicType({ code: "appType" }).then((res) => {
      this.appType = res.data.items;
    });
    this.queryPage();
  },
  methods: {
    changecode(key) {
      this.from[key] = codeReg(this.from[key]);
    },
    /**安装包*/
    handleAvatarSuccess1(res) {
      if (res.code === 1001) {
        console.log(res.data)
        this.appPackage = []
        this.from.appPackage = res.data.fileUrl
        this.TreeLoading = false
      }
    },
    beforeAvatarUpload1(file) {
      this.TreeLoading = true
      console.log(file)
    },
    /**二维码*/
    handleAvatarSuccess(res) {
      if (res.code === 1001) {
        this.imageUrl = res.data.fileUrl;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    qrcode(item) {
      this.qrimg = '/file/' + item
      this.qrimgvis = true
    },
    /*下载*/
    Download(url) {
      console.log(url)
      window.location.href = '/file/' + url;
    },
    /*更新排序号*/
    updateSortNum() {
      updateSortNum(this.sortIds).then(() => {
        this.queryPage();
      });
    },
    /*重置*/
    reset() {
      this.tableParam.code = "";
      this.tableParam.name = "";
      this.queryPage();
    },
    /*删除，禁用，启用，排序*/
    batchUpdateOrDelete(type, status) {
      if (this.ids.length == 0) {
        this.$message({
          message: "请选择要操作的数据项",
          type: "warning",
        });
        return;
      }
      if (type === "update_status") {
        this.$confirm("此操作将永久删除该APP?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        })
          .then(() => {
            batchUpdateOrDelete({
              ids: this.ids,
              status: status,
              type: type,
            }).then(() => {
              this.reset();
            });
          })
          .catch(() => { });
      } else {
        batchUpdateOrDelete({
          ids: this.ids,
          status: status,
          type: type,
        }).then(() => {
          this.queryPage();
        });
      }
    },
    /*保存或修改*/
    save() {
      if (this.TreeLoading == true) {
        this.$message({
          message: '请耐心等待文件上传完成！',
          type: 'warning'
        });
        return
      }
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          this.from.qrCode = this.imageUrl
          saveOrUpdate(this.from).then((res) => {
            if (res.code === 1001) {
              this.resefrom();
              this.queryPage();
              this.$message.success('添加成功');
            }
          });
        }
      });
    },
    resefrom() {
      this.dialogVisible = false;
    },
    /*获取列表*/
    queryPage() {
      queryPage(this.tableParam).then((res) => {
        this.total = res.data.totalRows;
        this.tableData = res.data.data;
      });
    },
    add() {
      this.dialogtitle = "添加APP";
      this.$data.from = this.$options.data().from;
      this.imageUrl = ''
      setTimeout(() => {
        this.$refs.dialogForm.clearValidate();
      }, 10);
      this.dialogVisible = true;
    },
    update(data) {
      let str = JSON.stringify(data);
      this.from = JSON.parse(str);
      this.from.enable = data.enable;
      this.imageUrl = this.from.qrCode
      this.dialogtitle = "修改APP";
      this.dialogVisible = true;
      str = null;
    },
    /*批量选择*/
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      this.sortIds = [];
      val.forEach((item) => {
        this.ids.push(item.id);
        this.sortIds.push({ id: item.id, sortNum: item.sortNum });
      });
    },
  },
  computed: {
    ...mapGetters({
      screenWidth: "getscreenWidth",
      screenHeight: "getscreenHeight",
      Collapse: "getsCollapse",
    }),
    style() {
      let num = 0;
      if (this.Collapse) {
        num = this.screenWidth - 124;
      } else {
        num = this.screenWidth - 220;
      }
      return "width:" + num + "px;";
    },
  },
};
</script>
<style lang="scss">
.APPmanagement {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>

<style lang="scss" scoped>
.APPmanagement {
  .dialoginfo {
    .el-input,
    .el-select {
      width: 200px;
    }
    .textarea_input {
      padding-top: 10px;
      align-items: flex-start;
      height: 118px;
    }
    .textarea {
      width: 500px;
    }
    .upload_bg {
      padding-top: 10px;
      align-items: flex-start;
      justify-content: flex-start;
      height: 210px;
    }
    .upload {
      width: 200px;
      height: 200px;
      position: relative;
      .upload_add {
        width: 200px;
        height: 200px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        background: #c1c1c1;
      }
      .input {
        margin: 0;
        position: absolute;
        top: 0;
        left: 0;
      }
      input {
        opacity: 0;
      }
    }
  }
}
</style>
